//
//  CheckPanelNumberAlertView.swift
//  ezyform
//
//  Created by MoennigQ on 5/11/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import Alamofire
import SnapKit
import SDWebImage
enum CheckPanelNumberType: String{
    case Edit = "Edit"//保存编辑后的code
    case Confirm = "Confirm"//不错任何处理,就使用当前的code，继续扫描
    case Delete = "Del" //不适用当前的扫描结果，重新扫描
}
class CheckPanelNumberAlertView: UIView {
    
    var continueClosure: ((_ type: CheckPanelNumberType,_ code: String )->Void)!
    var imageRequestList = [DataRequest]()
    
    let scrollView = UIScrollView()
    let codeImageView = UIImageView()
    let codeLabel = UILabel()
    let tipsLabel = UILabel()
    
    let radioBtnEdit = UIButton()
    let editTextfield = CustomTextfield()
    
    let toolBar = UIToolbar()
    let textfieldOnTopOfKeyboard = UITextView()
    
    let radioBtnIgnore = UIButton()
    let radioBtnDel = UIButton()
    
    let continueBtn = UIButton()
    //for code
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    //for storyboard
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUpView()
    }
    private func setUpView() {
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        //backView
        let backView = UIView()
        backView.backgroundColor = .white
        backView.layer.cornerRadius = 10
        backView.clipsToBounds = true
        self.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(40)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.bottom.equalToSuperview().offset(-40)
        }
        //title
        let titleLabel = UILabel()
        titleLabel.text = "Friendly Reminder"
        titleLabel.textColor = .black
        titleLabel.font = UIFont(name: "SFProText-Semibold", size: 17)
        titleLabel.textAlignment = .center
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        
        //continue btn
        continueBtn.isEnabled = false
        continueBtn.setImage(UIImage(named: "check_panelnumber_continue_disabled"), for: UIControl.State.normal)
        backView.addSubview(continueBtn)
        continueBtn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10)
            make.height.equalTo(64)
            make.width.equalTo(164)
            make.centerX.equalToSuperview()
        }
        //delete radio checkbox
        var attrString = NSMutableAttributedString(string: " Delete")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "SFProText-Regular", size: 15)!,.foregroundColor: UIColor(red: 0.15, green: 0.13, blue: 0.14,alpha:1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        radioBtnDel.setAttributedTitle(attrString , for: UIControl.State.normal)
        radioBtnDel.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
        radioBtnDel.contentHorizontalAlignment = .left
        backView.addSubview(radioBtnDel)
        radioBtnDel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.bottom.equalTo(continueBtn.snp.top).offset(-20)
            make.height.equalTo(40)
            make.width.equalTo(100)
        }
        //ignore radio checkbox
        attrString = NSMutableAttributedString(string: " Confirm")
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        radioBtnIgnore.setAttributedTitle(attrString , for: UIControl.State.normal)
        radioBtnIgnore.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
        radioBtnIgnore.contentHorizontalAlignment = .left
        backView.addSubview(radioBtnIgnore)
        radioBtnIgnore.snp.makeConstraints { (make) in
            make.left.equalTo(radioBtnDel)
            make.bottom.equalTo(radioBtnDel.snp.top)
            make.size.equalTo(radioBtnDel)
        }
        
        //edit radio checkbox
        attrString = NSMutableAttributedString(string: " Edit")
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        radioBtnEdit.setAttributedTitle(attrString , for: UIControl.State.normal)
        radioBtnEdit.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
        radioBtnEdit.contentHorizontalAlignment = .left
        backView.addSubview(radioBtnEdit)
        radioBtnEdit.snp.makeConstraints { (make) in
            make.left.equalTo(radioBtnDel)
            make.bottom.equalTo(radioBtnIgnore.snp.top)
            make.height.equalTo(radioBtnDel)
            make.width.equalTo(70)
        }
        
        //editTextfield
        backView.addSubview(editTextfield)
        editTextfield.snp.makeConstraints { (make) in
            make.left.equalTo(radioBtnEdit.snp.right)
            make.height.equalTo(45)
            make.centerY.equalTo(radioBtnEdit)
            make.right.equalToSuperview().offset(-20)
        }
        //tips
        //内容压缩阻力优先级越高，越难被压缩
        tipsLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: NSLayoutConstraint.Axis.vertical)
        tipsLabel.textColor = UIColor(red: 0.15, green: 0.13, blue: 0.14,alpha:1)
        tipsLabel.font = UIFont(name: "SFProText-Regular", size: 15)
        tipsLabel.numberOfLines = 0
        tipsLabel.textAlignment = .left
        backView.addSubview(tipsLabel)
        tipsLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(editTextfield.snp.top).offset(-10)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        //code
        codeLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: NSLayoutConstraint.Axis.vertical)
        codeLabel.textColor = UIColor(red: 0.91, green: 0.26, blue: 0.26,alpha:1)
        codeLabel.font = UIFont(name: "SFProText-Regular", size: 15)
        codeLabel.numberOfLines = 0
        codeLabel.textAlignment = .center
        backView.addSubview(codeLabel)
        codeLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(tipsLabel.snp.top).offset(-10)
            make.left.right.equalTo(tipsLabel)
            make.height.lessThanOrEqualTo(40)
        }
        //scrollView用于缩放图片
        scrollView.delegate = self
        scrollView.isUserInteractionEnabled = true
        scrollView.isScrollEnabled = true
        scrollView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        backView.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(codeLabel.snp.top).offset(-10)
        }
        //imageview，图片优先被压缩
        if let image = UIImage(named: "edit_panelnumber_loadingfailed"){
            self.codeImageView.image = image
        }
        codeImageView.contentMode = .scaleAspectFit
        scrollView.addSubview(codeImageView)
        
        //radio btn add target
        self.radioBtnEdit.addTarget(self, action: #selector(radioBtnEditClick(_:)), for: UIControl.Event.touchUpInside)
        self.radioBtnIgnore.addTarget(self, action: #selector(radioBtnIgnoreClick(_:)), for: UIControl.Event.touchUpInside)
        self.radioBtnDel.addTarget(self, action: #selector(radioBtnDelClick(_:)), for: UIControl.Event.touchUpInside)
        self.continueBtn.addTarget(self, action: #selector(continueBtnClick), for: UIControl.Event.touchUpInside)
        self.editTextfield.textView.delegate = self
        
        //
        self.addTextfieldOnKeyboard()
    }
    func addTextfieldOnKeyboard(){
        let doneImageWidth: CGFloat = 50
        let doneImageHeight: CGFloat = 45
        //光标颜色
        textfieldOnTopOfKeyboard.backgroundColor = .white
        textfieldOnTopOfKeyboard.tintColor = UIColor(red: 0.11, green: 0.82, blue: 0.66, alpha: 1.0)
        textfieldOnTopOfKeyboard.font = UIFont(name: "SFProText-Regular", size: 15)
        textfieldOnTopOfKeyboard.textColor = .black
        textfieldOnTopOfKeyboard.frame = CGRect(x: 0, y: 0, width: APPConfig.WidthForPortrait - doneImageWidth - 40, height: doneImageHeight)
        textfieldOnTopOfKeyboard.layer.borderWidth = 1
        textfieldOnTopOfKeyboard.layer.borderColor = UIColor.white.cgColor
        textfieldOnTopOfKeyboard.clipsToBounds = true
        textfieldOnTopOfKeyboard.layer.cornerRadius = 5
        textfieldOnTopOfKeyboard.delegate = self
        let editTextView = UIBarButtonItem(customView: textfieldOnTopOfKeyboard)
        
        let customBtn = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - doneImageWidth , y: 0, width: doneImageWidth, height: doneImageHeight))
        
        let attrString = NSMutableAttributedString(string: "OK")
        let attrNo: [NSAttributedString.Key : Any] = [.font: UIFont(name: "SFProText-Semibold", size: 17)!,.foregroundColor: UIColor(red: 0, green: 0, blue: 0,alpha:1)]
        attrString.addAttributes(attrNo, range: NSRange(location: 0, length: attrString.length))
        customBtn.setAttributedTitle(attrString, for: UIControl.State.normal)
        customBtn.addTarget(self, action: #selector(hideKeyBoard), for: UIControl.Event.touchUpInside)
        let doneButton = UIBarButtonItem(customView: customBtn)
        //tool bar
        self.toolBar.barTintColor = UIColor(red: 241 / 255, green: 241 / 255, blue: 241 / 255, alpha: 1.0)
        self.toolBar.barStyle = UIBarStyle.default
        self.toolBar.sizeToFit()
        
        toolBar.setItems([editTextView,doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        self.editTextfield.textView.inputAccessoryView = self.toolBar
        //光标颜色
        self.editTextfield.textView.tintColor = UIColor(red: 0.11, green: 0.82, blue: 0.66, alpha: 1.0)

    }
    @objc func hideKeyBoard(){
        self.textfieldOnTopOfKeyboard.resignFirstResponder()
        self.editTextfield.textView.text = self.textfieldOnTopOfKeyboard.text
        self.endEditing(true)
    }
    
    //btn click
    @objc
    func radioBtnEditClick(_ btn: UIButton){
        self.clickRadioOption(btn)
    }
    @objc
    func radioBtnIgnoreClick(_ btn: UIButton){
        self.clickRadioOption(btn)
    }
    @objc
    func radioBtnDelClick(_ btn: UIButton){
        self.clickRadioOption(btn)
    }
    //每次弹出提示时，要初始化UI，所有radio都不选择,
    func resetAlertUI(){
        self.radioBtnEdit.tag = 0
        self.radioBtnIgnore.tag = 0
        self.radioBtnDel.tag = 0
        
        self.radioBtnEdit.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
        self.radioBtnIgnore.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
        self.radioBtnDel.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
        
        self.editTextfield.makeTextfieldDisabled()
        self.continueBtn.isEnabled = false
        self.continueBtn.setImage(UIImage(named: "check_panelnumber_continue_disabled"), for: UIControl.State.normal)
        
        //重置contentSize
        self.resetContentSize()
    }
    fileprivate func resetContentSize(){
        //重置contentSize，解决下次的contentSize会默认使用上次的contentSize，导致图片显示有问题，例如：上传前图片分辨率很大，即contentSize很大；上传后进行了压缩，图片size会变小，但是contentSize还是上次的大size，会导致图片显示到左上角，重置后解决此问题
        self.scrollView.contentSize = self.scrollView.frame.size
        self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
    }
    func clickRadioOption(_ btn: UIButton){
        if btn.tag == 0{
            btn.tag = 1
            btn.setImage(UIImage(named: "owner_term_two_radiobox_sel"), for: UIControl.State.normal)
            if btn == self.radioBtnEdit{
                self.editTextfield.makeTextfieldAbled()
                self.editTextfield.textView.becomeFirstResponder()
                
            }
            //确保单选
            if btn != self.radioBtnEdit {
                self.radioBtnEdit.tag = 0
                self.radioBtnEdit.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
                self.editTextfield.makeTextfieldDisabled()
            }
            if btn != self.radioBtnIgnore {
                self.radioBtnIgnore.tag = 0
                self.radioBtnIgnore.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
            }
            if btn != self.radioBtnDel {
                self.radioBtnDel.tag = 0
                self.radioBtnDel.setImage(UIImage(named: "owner_term_two_radiobox"), for: UIControl.State.normal)
            }
            
        }
        if self.radioBtnDel.tag == 1 || self.radioBtnIgnore.tag == 1 || self.radioBtnEdit.tag == 1{
            let code = (self.editTextfield.textView.text ?? "")
            //选择Edit，但是编辑框内容为空，则continue不可用
            if self.radioBtnEdit.tag == 1, code == ""{
                self.continueBtn.isEnabled = false
                self.continueBtn.setImage(UIImage(named: "check_panelnumber_continue_disabled"), for: UIControl.State.normal)
            }else{
                self.continueBtn.isEnabled = true
                self.continueBtn.setImage(UIImage(named: "check_panelnumber_continue"), for: UIControl.State.normal)
            }
            
        }else{
            self.continueBtn.isEnabled = false
            self.continueBtn.setImage(UIImage(named: "check_panelnumber_continue_disabled"), for: UIControl.State.normal)
        }
    }
    @objc func continueBtnClick(){
        if self.radioBtnEdit.tag == 1{
            self.continueClosure(CheckPanelNumberType.Edit,self.editTextfield.textView.text ?? "")
        }else if self.radioBtnIgnore.tag == 1{
            self.continueClosure(CheckPanelNumberType.Confirm, "")
        }else if self.radioBtnDel.tag == 1{
            self.continueClosure(CheckPanelNumberType.Delete,"")
        }
    }
    func setData(_ panelModel: PanelNumberImageDBModel){
        self.codeLabel.text = panelModel.code
        self.tipsLabel.text = panelModel.error_history_message
        self.editTextfield.textView.text = panelModel.code
        self.editTextfield.makeTextfieldDisabled()
        if let _ = panelModel.id{//server
            if let imagePath = panelModel.image {
                guard let imageUrl = URL(string: imagePath) else {
                    return
                }
                Tool.sharedTool().showLoadingView()
                let request = AF.request(imageUrl).responseImage { resp in
                    Tool.sharedTool().hideLoadingView()
                    if case .success(let image) = resp.result {
                        self.codeImageView.image = image
                        self.resizeCodeImageView(false)
                    }else{
                        if let image = UIImage(named: "edit_panelnumber_loadingfailed"){
                            self.codeImageView.image = image
                        }
                        self.resizeCodeImageView(true)
                    }
                }
                self.imageRequestList.append(request)
            }else{
                if let image = UIImage(named: "edit_panelnumber_loadingfailed"){
                    self.codeImageView.image = image
                }
                self.resizeCodeImageView(true)
            }
            
        }else{//本地临时
            if let data = panelModel.imageData,let image = UIImage(data: data as Data){
                self.codeImageView.image = image
                self.resizeCodeImageView(false)
            }else{
                if let image = UIImage(named: "edit_panelnumber_loadingfailed"){
                    self.codeImageView.image = image
                }
                self.resizeCodeImageView(true)
            }
            
        }
        
    }
    //加载完图片后，将code imageview显示在scrollview的中间位置,
    //loadFaildFlag： true表示加载失败的默认图片，zoom属性特别设置
    func resizeCodeImageView(_ loadFaildFlag: Bool){
        self.scrollView.contentSize = self.codeImageView.image!.size
        
        let scrollViewFrame = scrollView.frame
        let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
        let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
        //
        var minScale: CGFloat = 0
        
        if loadFaildFlag {//加载失败的默认图片，zoom竖向全部设置为1，不可以缩放
            minScale = 1
            scrollView.maximumZoomScale = minScale
        }else{
            minScale = min(scaleWidth, scaleHeight)
            scrollView.maximumZoomScale = minScale * 10
        }
        scrollView.minimumZoomScale = minScale
        scrollView.zoomScale = minScale
        let x = (self.scrollView.frame.size.width - self.codeImageView.image!.size.width * minScale) / 2
        let y = (self.scrollView.frame.size.height - self.codeImageView.image!.size.height * minScale) / 2
        self.codeImageView.frame = CGRect(x:  x, y: y, width:  self.codeImageView.image!.size.width * minScale , height: self.codeImageView.image!.size.height * minScale)
        //重置contentSize
        self.resetContentSize()
    }
    
    //取消所有的image 网络请求,防止APP端本地检查的提醒图片被延迟的图片加载覆盖掉
    func cancelAllImageRequest(){
        if self.imageRequestList.count > 0 {
            for task in self.imageRequestList{
                task.cancel()
            }
            self.imageRequestList.removeAll()
        }
        self.codeImageView.image = nil
    }
}
extension CheckPanelNumberAlertView: UITextViewDelegate,UIScrollViewDelegate{
    //UITextViewDelegate
    func textViewDidChange(_ textView: UITextView) {
        if textView == self.textfieldOnTopOfKeyboard{
            let code = (self.textfieldOnTopOfKeyboard.text ?? "").trimmingCharacters(in: .whitespaces)
            if code == ""{
                self.continueBtn.isEnabled = false
                self.continueBtn.setImage(UIImage(named: "check_panelnumber_continue_disabled"), for: UIControl.State.normal)
            }else{
                self.continueBtn.isEnabled = true
                self.continueBtn.setImage(UIImage(named: "check_panelnumber_continue"), for: UIControl.State.normal)
            }
            self.editTextfield.textView.text = code
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView == self.textfieldOnTopOfKeyboard && text == "\n"{
            self.hideKeyBoard()
            return false
        }
        return true
    }
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if textView == self.editTextfield.textView{
            textView.resignFirstResponder()
            self.textfieldOnTopOfKeyboard.text = textView.text
        }
        return true
    }
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView == self.editTextfield.textView{
            self.textfieldOnTopOfKeyboard.becomeFirstResponder()
        }
    }
    //UIScrollViewDelegate
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.codeImageView
    }
    //缩放后，重新设置codeImageView的frame，防止留白
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        //zoom后imageview size大于scrollview的size
        if(self.codeImageView.frame.size.width >= self.scrollView.frame.size.width && self.codeImageView.frame.size.height >= self.scrollView.frame.size.height){
            self.codeImageView.frame = CGRect(x: 0, y: 0, width: self.codeImageView.frame.size.width, height: self.codeImageView.frame.size.height)
        }else if self.codeImageView.frame.size.width < self.scrollView.frame.size.width {//否则zoom后imageview width大于scrollview的width
            self.codeImageView.frame = CGRect(x: (self.scrollView.frame.size.width - self.codeImageView.frame.size.width) / 2, y: self.codeImageView.frame.origin.y, width: self.codeImageView.frame.size.width, height: self.codeImageView.frame.size.height)
        }else if self.codeImageView.frame.size.height < self.scrollView.frame.size.height {//否则zoom后imageview height大于scrollview的height
            self.codeImageView.frame = CGRect(x: self.codeImageView.frame.origin.x, y: (self.scrollView.frame.size.height -  self.codeImageView.frame.size.height) / 2, width: self.codeImageView.frame.size.width, height: self.codeImageView.frame.size.height);
        }
    }
}
